package com.starwish.starwishblog.web.back;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.starwish.starwishblog.result.ResultResponse;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("admin/getCode")
public class CodeController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    StringRedisTemplate stringRedisTemplate ;

    @GetMapping
    public ResultResponse<String> getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ResultResponse<String> result = null;
        // 设置浏览器缓存机制
        response.setHeader("Cache-Control", "no-store, no-cache");
        // 设置返回响应类型
        response.setContentType("image/jpeg");
        // 生成验证码
        String code = defaultKaptcha.createText();
        // 获取当前请求的会话，将生成的验证码保存到当中
        stringRedisTemplate.opsForValue().set("code",code);

//        HttpSession session = request.getSession();
//        session.setAttribute("code", code);
//        System.err.println("传之前============================"+session.getAttribute("code"));

        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(code);
        // 转为Base64
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", stream);
        String imgString = "data:image/gif;base64," + Base64.encode(stream.toByteArray());
        stream.flush();
        stream.close();
        // 将数据存入并将其返回
        result = new ResultResponse<>(200, "加载成功",imgString);
        return result;
//        return new ResultResponse<String>(200, "", imgString);
    }
}
